import {
  getPage
} from '../../utils/config';
import api from '../../utils/api';
import {
  http,
  $empty,
  $toast,
  storage,
  Validate
} from '../../utils/utils';
import wxApi from '../../utils/wxApi';
import uploadImage from '../../utils/aliyunoss/uploadAliyun';
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    regionInfo: [],
    pickerArea: true,
    areaShow: false,
    shoptypeShow: false,
    pickerValue: '110101',
    bankValue: '',
    columns: [],
    shoptype: 2,
    shoptypetext: '建材门店',
    shoptypecolumns: ['建材门店', '装修公司', '设计师'],
    areaList: {
      province_list: {},
      city_list: {},
      county_list: {},
    },
    addressForm: {
      realname: '',
      idcardno: '',
      bank: '',
      tel: '',
      Address: '',
      bankno: '',
      location: '',
      locationId: [],
    },

  },
  onChange(event) {
    const {
      picker,
      value,
      index
    } = event.detail;
    this.setData({
      banknoError: '',
      'addressForm.bank': value
    });
    //Toast(`当前值：${value}, 当前索引：${index}`);
  },

  onTypeChange(event) {
    const {
      picker,
      value,
      index
    } = event.detail;
    console.log(index);
    this.setData({
      shoptypeError: '',
      'shoptype': index + 2,
      'shoptypetext': value
    });
    //Toast(`当前值：${value}, 当前索引：${index}`);
  },

  toggle(type) {
    this.setData({
      [type]: !this.data[type]
    });
  },

  /**
   * 城市选择open || close
   */
  pickerAreaTap() {
    this.toggle('areaShow');
  },

  /**
   * 城市选择open || close
   */
  pickerBankTap() {
    this.toggle('bankShow');
  },
  pickerShopTypeTap() {
    this.toggle('shoptypeShow');
  },

  /**
   * 确定选择城市
   */
  pickerAreaConfirm(e) {
    const {
      index,
      values
    } = e.detail;
    const {
      regionInfo
    } = this.data;
    const provice = regionInfo[index[0]];
    const city = provice.list[index[1]];
    const county = city.list[index[2]];
    this.setData({
      locationError: '',
      'addressForm.location': `${provice.name} ${city.name} ${county.name}`,
      'addressForm.locationId': [provice.id, city.id, county.id],
    });
    this.pickerAreaTap();
  },

  /**
   * 收货人
   */
  realnameInput(e) {
    this.setData({
      realnameError: '',
      'addressForm.realname': $empty(e.detail)
    })
  },
  /**
   * 收货人
   */
  shopnameInput(e) {
    this.setData({
      shopnameError: '',
      'addressForm.shopname': $empty(e.detail)
    })
  },

  /**
   * 身份证号码
   */
  // idcardnoInput(e) {
  //   this.setData({
  //     idcardnoError: '',
  //     'addressForm.idcardno': $empty(e.detail)
  //   })
  // },

  AddressInput(e) {
    this.setData({
      AddressError: '',
      'addressForm.Address': $empty(e.detail)
    })
  },
  kaihuhangInput(e) {
    this.setData({
      kaihuhangError: '',
      'addressForm.kaihuhang': $empty(e.detail)
    })
  },
  banknoInput(e) {
    this.setData({
      banknoError: '',
      'addressForm.bankno': $empty(e.detail)
    })
  },
  shoptypeInput(e) {
    this.setData({
      shoptypeError: '',
      'shoptypetext': $empty(e.detail)
    })
  },
  telInput(e) {
    this.setData({
      telError: '',
      'addressForm.tel': $empty(e.detail)
    })
  },
  /**
   * 所在地址
   */
  locationInput(e) {
    this.setData({
      locationError: '',
      'addressForm.location': e.detail
    })
  },
  /**
   * 替换头像
   */
  modifyshopAvatar() {
    const that = this;
    let {
      shop,
      avatar
    } = this.data;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        wx.showModal({
          content: '确定上传店铺头像？',
          success(res) {
            if (res.confirm) {
              uploadImage({
                filePath: tempFilePaths[0],
                dir: "users",
                success(res) {
                  avatar = res;
                  that.setData({
                    avatar
                  });
                  //更新用户头像
                  that.setUserInfo(() => {
                    $toast('店铺头像保存成功', {
                      icon: 'success'
                    });
                  });
                },
                fail(res) {
                  $toast(`店铺头像上传失败` + JSON.stringify(res));
                }
              });
            }
          }
        })
      }
    });
  },

  /**
   * 更新用户信息
   */
  setUserInfo(cb) {
    const {
      userId,
      avatar,
      rank
    } = this.data;
    const userInfo = this.data.userInfo;
    http.post(api.default, {
      data: {
        action: 'updateshopavatar',
        userid: userId,
        avatar: avatar,
        rank: rank
      }
    }).then((res) => {
      if (res.data.code == 0) {
        userInfo.data.shop.picurl = res.data.data.picurl;
        storage.set('userInfo', userInfo);
      }
      cb && cb(res);
      this.setData({
        pageChange: 1
      });
    });
  },
  /**
   * 提交保存
   */
  addressForm(e) {
    Validate.check(this, this.addressValidate, e.detail.value, (res) => {
      console.log(res);
      if (res) {
        const data = this.data;
        const userInfo = data.userInfo;

        const {
          realname,
          idcardno,
          tel,
          Address,
          bankno,
          shopname,
          locationId
        } = data.addressForm;
        const params = {
          action: 'shenqing',
          realname: realname,
          //idcardno: idcardno,
          tel: tel,
          Address: Address,
          bankno: bankno,
          province_id: locationId[0],
          city_id: locationId[1],
          district_id: locationId[2],
          birthday: data.selectDate,
          userid: data.userId,
          rank: data.rank,
          shopname
        }


        http.post(api.default, {
          data: params
        }).then((res) => {
          if (res.data.code == 0) {
            userInfo.data.shop = res.data.data;
            storage.set('userInfo', userInfo);
            $toast('修改成功', {
              icon: 'success'
            });
            const pages = getCurrentPages()[getCurrentPages().length - 3];

            wx.navigateBack({
              delta: 2,
              success() {
                if (pages !== undefined || pages !== null) {
                  pages.data.pageChange = 1;
                  pages.onLoad();
                }
              }
            });
          } else {
            $toast(res.data.errmsg, {
              icon: 'fail'
            });

          }
        });
      }
    });
  },
  /**
   * 获取地区
   */
  getRegionInfo() {
    return new Promise((resolve) => {
      storage.get('regionInfo').then((res) => {
        this.setData({
          regionInfo: res,
          pickerArea: false
        });
        resolve(res);
      }).catch((res) => {
        http.get(api.default, {
          data: {
            action: 'district'
          }
        }, false).then((res) => {
          const {
            data
          } = res.data;
          this.setData({
            regionInfo: data,
            pickerArea: false
          });
          storage.set('regionInfo', data);
          resolve(data);
        });
      });
    });
  },
  /**
   * 城市数据格式转换
   * @整体是一个 Object，包含 province_list, city_list, county_list 三个 key。
   * @每项以省市区编码作为 key，省市区名字作为 value。编码为 6 位数字，前两位代表省份，中间两位代表城市，后两位代表区县，以 0 补足 6 位。如北京编码为 11，以零补足 6 位，为 110000。
   */
  formatArea() {
    const {
      regionInfo,
      areaList
    } = this.data;
    let {
      province_list,
      city_list,
      county_list
    } = areaList;

    //一级 省份
    regionInfo.forEach((parentsItem, parentsIndex) => {
      parentsIndex = (parentsIndex + 11).toString();
      let parentsCode = parentsIndex;
      let parentsLength = parentsIndex.length;
      if (parentsLength < 6) {
        for (let i = 0; i < 6 - parentsLength; i++) {
          parentsCode = parentsCode + `0`;
        }
      }

      //二级 城市
      if (parentsItem.list.length) {
        parentsItem.list.forEach((parentItem, parentIndex) => {
          //从1开始
          parentIndex = (parentIndex + 1).toString();
          if (parentIndex < 10) {
            parentIndex = `0` + parentIndex;
          }
          parentIndex = parentsIndex + parentIndex;
          let parentCode = parentIndex;
          let parentLength = parentIndex.length;
          if (parentLength < 6) {
            for (let i = 0; i < 6 - parentLength; i++) {
              parentCode = parentCode + `0`;
            }
          }
          city_list[parentCode] = parentItem.name;

          //三级 区
          if (parentItem.list.length) {
            parentItem.list.forEach((item, index) => {
              //从1开始
              index = (index + 1).toString();
              if (index < 10) {
                index = `0` + index;
              }
              index = parentIndex + index;
              let code = index;
              let length = index.length;
              if (length < 6) {
                for (let i = 0; i < 6 - length; i++) {
                  code = code + `0`;
                }
              }
              county_list[code] = item.name
            });
          }
        });
      }
      province_list[parentsCode] = parentsItem.name;
    });

    this.setData({
      areaList
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    //判断入口是否带参数
    if (options && JSON.stringify(options) !== '{}') {
      this.setData({
        rank: options.id
      });
      var title = "商家入驻";
      if (options.id == 2) {
        title = "申请成为建材门店"
      } else if (options.id == 3) {
        title = "申请成为装修公司"
      } else if (options.id == 4) {
        title = "申请成为设计师"
      }

      wx.setNavigationBarTitle({
        title: title
      })

    }
    // http.get(api.default, {
    //   data: {
    //     action: 'getchinabanks'
    //   }
    // }, false).then((res) => {
    //   console.log(res);
    //   this.setData({
    //     columns: res.data.data
    //   });
    // });
    app.getLogin().then((res) => {
      console.log(res.data);
      if (res.data.shop == null)
        res.data.shop = {};
      var zonedata = res.data.shop.zonedata;

      var location = "";
      var locationId = [];
      if (zonedata == null)
        zonedata = [];
      const {
        province,
        district,
        city
      } = zonedata;
      if (zonedata.province != null) {
        location = `${province.name} ${city.name} ${district.name}`;
        locationId = [province.id, city.id, district.id];
      }

      this.setData({
        userInfo: res,
        logged: res.code,
        userId: res.data.user.user_id,
        avatar: res.data.shop.picurl == null ? "" : res.data.shop.picurl,
        zonedata: res.data.shop.zonedata,
        addressForm: {
          realname: res.data.shop.Contacter,
          //idcardno: res.data.shop.idcardno,
          Address: res.data.shop.Address,
          kaihuhang: res.data.user.kaihuhang,
          tel: res.data.shop.Tel,
          location: location,
          locationId: locationId,
        }
      });
    }).catch((res) => {
      this.setData({
        logged: res,
      });
      this.goLogin();
    })


    /**
     * 获取地区
     */
    this.getRegionInfo().then((res) => {
      //地区格式化
      this.formatArea();
      //如果修改地址

      const data = this.data;
      if (data.zonedata != null) {
        const {
          district
        } = data.zonedata;
        const {
          county_list
        } = data.areaList;
        Object.entries(county_list).map((key) => {
          if (district.name == key[1]) {
            this.setData({
              pickerValue: key[0],
            })
          }
        })
      }
    });

    /**
     * 收货地址保存
     */
    Validate.rules('#realname,#idcardno,#shoptype,#tel,#location,#Address', (res) => {
      this.addressValidate = res;
    });
  },
  /**
   * 跳转登录
   */
  goLogin() {
    wxApi.setStartPage();
    wxApi.navigateTo(getPage.login);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  }
})